<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\api\controller\ding;

use app\api\controller\Controller;
use app\api\model\ding\ClerkMember as ClerkMemberModel;
use app\api\model\ding\Order as OrderModel;
use app\api\model\store\shop\Clerk as ClerkModel;
use app\api\model\wxapp\Setting as WxappSettingModel;
use app\api\service\User as UserService;
use app\common\service\qrcode\Card as CradPoster;
use think\facade\Db;
use think\response\Json;

/**
 * 购物车管理
 * Class Cart
 * @package app\api\controller
 */
class Clerk extends Controller
{

    public function poster(string $channel = 'MP-WEIXIN', int $shopId = 0): Json
    {
        $user  = UserService::getCurrentLoginUser(true);
        $clerk = ClerkModel::detail(['user_id' => $user['user_id'], 'shop_id' => $shopId], ['shop.logoImage', 'user.avatar', 'shop.cardImage']);

        // 获取当前小程序信息
        $config = self::getMpWxConfig();

        // 微信登录 (获取session_key)
        // $WxUser = new Link($config['app_id'], $config['app_secret']);

        // $param['page_url'] = 'pagesNew/shop/share?' . 'clerkId=' . $clerk['clerk_id'] . '&shopId=' . $clerk['shop_id'];
        // $param['page_title'] = '找我预订';
        // $param['is_permanent'] = true;
        // $result = $WxUser->getLink($param);

        $clerk['content'] = '尊敬的顾客您好，我是' . $clerk['shop']['shop_name'] . '的' . $clerk['real_name'] . '，欢迎来找我预订包间。点击找我一键预订包间→' . $clerk['url'];

        // 生成商品海报图
        $userId = UserService::getCurrentLoginUserId();
        $Qrcode = new CradPoster($clerk, $channel);
        return $this->renderSuccess(['imageUrl' => $Qrcode->getImage(), 'clerk' => $clerk]);
    }

    /**
     * 获取微信小程序配置项
     * @return array
     * @throws \cores\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */

    private static function getMpWxConfig(): array
    {
        $wxConfig = WxappSettingModel::getWxappConfig();
        if (empty($wxConfig['app_id']) || empty($wxConfig['app_secret'])) {
            throwError('请到后台小程序设置填写AppID和AppSecret参数');
        }
        return $wxConfig;
    }

    public function shopList(): Json
    {
        $user    = UserService::getCurrentLoginUser(true);
        $service = new ClerkModel;

        $list = $service->getListClerk($user['user_id']);

        return $this->renderSuccess(compact('list'));
    }

    public function list(int $shopId = 0): Json
    {

        $service = new ClerkModel;

        $list = $service->getList($shopId);

        return $this->renderSuccess(compact('list'));
    }
    /*
		*销售排名
	*/
    public function rankList($date = 0, int $shopId = 0): Json
    {

        $service = new ClerkModel;

        $list = $service->rankList($shopId, $date);

        return $this->renderSuccess(compact('list'));
    }
    public function kehuList(): Json
    {

        $model = new ClerkMemberModel();
        $list  = $model->getList($this->request->param());

        return $this->renderSuccess(compact('list'));
    }
    public function memberHistory($userId = 0, $mobile = '', int $shopId = 0): Json
    {

        $model = new ClerkMemberModel();
        $list  = $model->getListHistory($userId,$mobile,$shopId);

        return $this->renderSuccess(compact('list'));
    }
    public function memberDetail($id = 0, $orderId = 0, int $shopId = 0): Json
    {
        $user = UserService::getCurrentLoginUser(true);
        $shop = Db::name('store_shop_clerk')
            ->where('user_id', $user['user_id'])
            ->where('shop_id', $shopId)
            ->field('shop_id,clerk_id')->find();
        if ($id == 0) {
            $order  = OrderModel::detail($orderId);
            $detail = Db::name('ding_clerk_member')->where('shop_id', $shop['shop_id'])->where('mobile', $order['mobile'])->where('is_delete', 0)->find();
            if (! $detail) {
                $detail['shop_id']     = $shop['shop_id'];
                $detail['clerk_id']    = $shop['clerk_id'];
                $detail['mobile']      = $order['mobile'];
                $detail['real_name']   = $order['real_name'];
                $detail['store_id']    = $order['store_id'];
                $detail['create_time'] = time();
                $id                    = Db::name('ding_clerk_member')->insertGetId($detail);

            } else {
                $id = $detail['id'];
            }

        }

        $detail = ClerkMemberModel::detail($id);
        if ($detail) {
            $detail['clerk_times'] = Db::name('ding_order')->where('clerk_id', $shop['clerk_id'])
                ->where('mobile', $detail['mobile'])->count();

            $detail['times'] = Db::name('ding_order')->where('shop_id', $shop['shop_id'])
                ->where('mobile', $detail['mobile'])->count();
            if ($detail['times'] > 0) {
                $time = Db::name('ding_order')->where('shop_id', $shop['shop_id'])
                    ->where('mobile', $detail['mobile'])->order('id desc')->value('create_time');
                $detail['yuding_time'] = date('Y-m-d', $time);
            }

            $detail['times_clerk'] = Db::name('ding_order')->where('shop_id', $shop['shop_id'])->where('clerk_id', $shop['clerk_id'])
                ->where('mobile', $detail['mobile'])->count();

            if ($detail['times_clerk'] > 0) {
                $time = Db::name('ding_order')->where('shop_id', $shop['shop_id'])->where('clerk_id', $shop['clerk_id'])
                    ->where('mobile', $detail['mobile'])->order('id desc')->value('create_time');
                $detail['yuding_time_clerk'] = date('Y-m-d', $time);
            }
        }

        return $this->renderSuccess(['detail' => $detail], '成功');
    }
    public function detail_bind(int $shopId = 0): Json
    {
        $user  = UserService::getCurrentLoginUser(true);
        $clerk = ClerkModel::detail(['shop_id' => $shopId, 'user_id' => $user['user_id'], 'is_delete' => 0], ['shop', 'user.avatar', 'role']);

        return $this->renderSuccess(['clerk' => $clerk], '成功');
    }
    public function detail(int $clerkId = 0): Json
    {
        if ($clerkId == 0) {
            $user  = UserService::getCurrentLoginUser(true);
            $clerk = ClerkModel::detail(['user_id' => $user['user_id'], 'is_delete' => 0], ['shop', 'user.avatar', 'role']);
        } else {
            $clerk = ClerkModel::detail(['clerk_id' => $clerkId], ['shop', 'user.avatar', 'role']);
        }

        return $this->renderSuccess(['clerk' => $clerk], '成功');
    }
    //我的数据
    public function staticData(int $shopId = 0): Json
    {
        $user  = UserService::getCurrentLoginUser(true);
        $clerk = ClerkModel::detail(['user_id' => $user['user_id'], 'shop_id' => $shopId]);

        // 检索查询条件
        $filter   = [];
        $filter[] = ['shop_id', '=', $shopId];
        $filter[] = ['clerk_id', '=', $clerk['clerk_id']];

        $kehu = Db::name('ding_clerk_member')->where($filter)->count();

        $time     = time() - 30 * 86400;
        $kehu_die = Db::name('ding_clerk_member')
            ->where($filter)
            ->where('update_time', '<', $time)

            ->count();

        $static['total_kehu'] = $kehu;
        $static['die_kehu']   = $kehu_die;
        //待转化
        $static['wait_member'] = 0;

        //查看有效期

        $shop = Db::name('store_shop')->where('shop_id', $shopId)->find();

        $day = round(($shop['end_date'] - time()) / 86400);

        $setting_day = Db::name('store')->value('day');
        $is_tixing   = 0;
        if ($day <= $setting_day) {
            $is_tixing = 1;
        }
        if ($setting_day == 0) {
            $is_tixing = 0;
        }

        return $this->renderSuccess(['static' => $static, 'is_tixing' => $is_tixing, 'day' => $day], '成功');
    }
    //门店数据
    public function shopData(int $shopId = 0): Json
    {
        $user  = UserService::getCurrentLoginUser(true);
        $clerk = ClerkModel::detail(['user_id' => $user['user_id'], 'shop_id' => $shopId]);

        // 检索查询条件
        $filter   = [];
        $filter[] = ['shop_id', '=', $shopId];
        $filter[] = ['clerk_id', '=', 0];
        $filter[] = ['is_delete', '=', 0];

        $kehu = Db::name('ding_clerk_member')->where($filter)->count();

        $time     = time() - 30 * 86400;
        $kehu_die = Db::name('ding_clerk_member')
            ->where($filter)
            ->where('update_time', '<', $time)
            ->where('is_delete',0)
            ->count();

        $static['total_kehu'] = $kehu;
        $static['die_kehu']   = $kehu_die;

        //待转化
        $static['wait_member'] = 0;
        //查看有效期

        $shop = Db::name('store_shop')->where('shop_id', $shopId)->find();

        $day = round(($shop['end_date'] - time()) / 86400);

        $setting_day = Db::name('store')->value('day');
        $is_tixing   = 0;
        if ($day <= $setting_day) {
            $is_tixing = 1;
        }
        if ($setting_day == 0) {
            $is_tixing = 0;
        }

        return $this->renderSuccess(['static' => $static, 'is_tixing' => $is_tixing, 'day' => $day], '成功');
    }

    public function edit(int $clerkId = 0): Json
    {

        $model = ClerkModel::detail($clerkId);

        $model->edit($this->postForm());
        return $this->renderSuccess([], '设置成功');
    }
    public function editMember(int $memberId): Json
    {

        $model = ClerkMemberModel::detail($memberId);

        $model->edit($this->postForm());
        return $this->renderSuccess([], '保存成功');
    }

    public function move(int $clerkId = 0): Json
    {
        Db::name('store_shop_clerk')->where('clerk_id', $clerkId)->update(['is_delete' => 1]);

        return $this->renderSuccess([], '移除成功');
    }

}
